import React from 'react'
import ReactDOM from 'react-dom'

let map, mapWrapper

const getMapRoot = () => {
  let dom = document.getElementById('map-root')
  if (!dom) {
    dom = document.createElement('div')
    dom.id = 'map-root'
    document.body.appendChild(dom)
  }
  return dom
}

const AppendMarker = (center) => {
  AMapUI.loadUI(['overlay/SimpleMarker'], Marker => {
    new Marker({
      iconStyle: {
        src: '/static/marker.svg',
        style: { width: '40px', height: '30px' }
      },
      map,
      position: center,
      zIndex: 200
    });
  })
}

const configMap = ({ center, x, y }) => {
  map.setCenter(center)
  if (x > 700) {
    x = x - 320
    y = y + 70
  }

  if (y > document.body.offsetHeight - window.innerHeight / 3 * 2) {
    y = y - 460
    if (x < 700) {
      y = y + 300
    }
  }
  mapWrapper.style.left = x + 'px'
  mapWrapper.style.top = y + 'px'
  AppendMarker(center)
}

const handleClose = () => {
  ReactDOM.unmountComponentAtNode(getMapRoot())
  map = null
  mapWrapper = null
}

class MapInner extends React.Component {
  $mapInstance = React.createRef()
  $mapWrapper = React.createRef()

  defaultZoom = 17

  componentDidMount() {
    const zoom = this.defaultZoom
    mapWrapper = this.$mapWrapper.current
    map = new AMap.Map(this.$mapInstance.current, { zoom })

    configMap(this.props)
  }

  componentWillUnmount(){
    handleClose()
  }

  render() {
    return (
      <div className="map-wrapper" ref={this.$mapWrapper}>
        <div id="map-instance" ref={this.$mapInstance} style={{ width: 600, height: 400 }}></div>
        <div className="map-wrapper-close" onClick={handleClose}>+</div>
      </div>
    )
  }
}

const Map = {
  show: opt => {
    if (map && mapWrapper) {
      configMap(opt)
    } else {
      ReactDOM.render(<MapInner {...opt} />, getMapRoot())
    }
  },
  close: handleClose
}

export default Map